package com.fancy.learncenter.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.AllSchoolDataBean;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.BindResultDataBean;
import com.fancy.learncenter.bean.SchoolAreaDeatailBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.ui.adapter.base.CustomViewHold;
import com.fancy.learncenter.ui.view.BasePopupWindow;
import com.fancy.learncenter.ui.view.BindSchoolPopupwindow;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class BindSchoolActivity extends BaseActivity {


    @Bind(R.id.recyclerview_pro)
    RecyclerView recyclerviewPro;
    @Bind(R.id.recyclerview_city)
    RecyclerView recyclerviewCity;

    String name;
    long cityId;

    String types;

    @Bind(R.id.activity_bind_school)
    RelativeLayout activityBindSchool;

    BindSchoolPopupwindow basePopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_school, Status.STATUS);
        name = getIntent().getStringExtra("name");
        cityId = getIntent().getLongExtra("id", 0);
        initToolbar(name);

        setRight("筛选", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.show("开始筛选");
                if (basePopupWindow == null) {
                    basePopupWindow = new BindSchoolPopupwindow(BindSchoolActivity.this, activityBindSchool, new BindSchoolPopupwindow.BindSchoolCallBack() {
                        @Override
                        public void learn() {
                            types = "2";

                            getAllSchool();
                        }

                        @Override
                        public void ngl() {
                            types = "1";
                            getAllSchool();
                        }

                        @Override
                        public void all() {
                            types = "";
                            getAllSchool();
                        }
                    });
                }

                basePopupWindow.showPopupWindow();
            }
        });
        ButterKnife.bind(this);
        initProAndCityView();

        getAllSchool();
    }

    ArrayList<AllSchoolDataBean.AreaVOListBean> areaDatas;
    ArrayList<SchoolAreaDeatailBean> schoolDatas;

    SchoolAdapter schoolAdapter;
    AreaAdapter areaAdapter;

    private void initProAndCityView() {
        areaDatas = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerviewPro.setLayoutManager(manager);
        areaAdapter = new AreaAdapter(this, areaDatas);
        recyclerviewPro.setAdapter(areaAdapter);


        schoolDatas = new ArrayList<>();
        LinearLayoutManager manager2 = new LinearLayoutManager(this);
        manager2.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerviewCity.setLayoutManager(manager2);
        schoolAdapter = new SchoolAdapter(this, schoolDatas);
        recyclerviewCity.setAdapter(schoolAdapter);
    }


    class AreaAdapter extends CommonRecycleViewAdapter<AllSchoolDataBean.AreaVOListBean> {

        public AreaAdapter(Context mContext, List<AllSchoolDataBean.AreaVOListBean> itemDatas) {
            super(mContext, R.layout.textview_item, itemDatas);
        }

        @Override
        public void bindView(CustomViewHold customViewHold, final AllSchoolDataBean.AreaVOListBean item, final int position) {
            TextView name = (TextView) customViewHold.getRoorView();
            name.setText(item.getName());
            if (item.isSelected()) {
                name.setBackgroundColor(Color.parseColor("#FFFFFF"));
                name.setTextColor(getResources().getColor(R.color.yello));
            } else {
                name.setBackgroundColor(Color.parseColor("#FAFAFA"));
                name.setTextColor(getResources().getColor(R.color.bind_text_color));
            }

            name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < areaDatas.size(); i++) {
                        if (areaDatas.get(i).isSelected()) {
                            areaDatas.get(i).setSelected(false);
                            notifyItemChanged(i);
                        }
                    }
                    areaDatas.get(position).setSelected(true);
                    notifyItemChanged(position);
                    getAllSchool(cityId, item.getId(), types);
                }
            });
        }
    }

    class SchoolAdapter extends CommonRecycleViewAdapter<SchoolAreaDeatailBean> {

        public SchoolAdapter(Context mContext, List<SchoolAreaDeatailBean> itemDatas) {
            super(mContext, R.layout.activity_bind_school_item, itemDatas);
        }

        @Override
        public void bindView(CustomViewHold customViewHold, final SchoolAreaDeatailBean item, int position) {
            TextView name = customViewHold.getView(R.id.name);
            name.setText(item.getSchoolName());

            TextView bindIcon = customViewHold.getView(R.id.bind_icon);

            if (Constant.isBind) {
                bindIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bindSchool(item.getSchoolId(), item.getSchoolName());

                    }
                });
            } else {
                bindIcon.setVisibility(View.GONE);
                customViewHold.getRoorView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent(BindSchoolActivity.this, CourseDetailActivity.class);
                        Constant.schoolName = item.getSchoolName();
                        Constant.schoolID = item.getSchoolId() + "";
                        startActivity(intent);

                        finish();
                    }
                });
            }

        }
    }

    /**
     * @param cityId
     * @param areaId -1 获取全部学校
     * @param types  学校类型:ngl:1,学习中心:2, 全部:不传
     */
    private void getAllSchool(long cityId, long areaId, String types) {
        Map map = new HashMap();
        map.put("cityId", cityId);
        //不传区域areaId，获取全部学校
        if (areaId != -1) {
            map.put("areaId", areaId);
        }
        if (!TextUtils.isEmpty(types)) {
            map.put("types", types);
        }

        HttpMehtod.getInstance().getAllSchool(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<AllSchoolDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), AllSchoolDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<AllSchoolDataBean>() {
                    @Override
                    public void success(AllSchoolDataBean dataBean) {
                        schoolDatas.removeAll(schoolDatas);
                        schoolDatas.addAll(dataBean.getSchoolAreaVOList());
                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();
            }

            @Override
            public void onCompleted() {
                super.onCompleted();

                schoolAdapter.notifyDataSetChanged();

            }
        });
    }

    private void getAllSchool() {
        Map map = new HashMap();
        map.put("cityId", cityId);
        if (!TextUtils.isEmpty(types)) {
            map.put("types", types);
        }


        HttpMehtod.getInstance().getAllSchool(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<AllSchoolDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), AllSchoolDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<AllSchoolDataBean>() {
                    @Override
                    public void success(AllSchoolDataBean dataBean) {
                        areaDatas.removeAll(areaDatas);
                        schoolDatas.removeAll(schoolDatas);

                        AllSchoolDataBean.AreaVOListBean allBean = new AllSchoolDataBean.AreaVOListBean();
                        allBean.setName("全部");
                        allBean.setId(-1);
                        allBean.setSelected(true);
                        areaDatas.add(allBean);
                        areaDatas.addAll(dataBean.getAreaVOList());

                        schoolDatas.addAll(dataBean.getSchoolAreaVOList());
                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();
            }

            @Override
            public void onCompleted() {
                super.onCompleted();

                areaAdapter.notifyDataSetChanged();
                schoolAdapter.notifyDataSetChanged();

            }
        });
    }

    /**
     * 绑定学校
     *
     * @param school
     */
    private void bindSchool(final long school, final String schoolName) {
        HttpMehtod.getInstance().bindSchool(school, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
//                //解析数据
                BaseBean<BindResultDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), BindResultDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<BindResultDataBean>() {
                    @Override
                    public void success(BindResultDataBean dataBean) {

                        if (dataBean.getBindingResult() == 1) {

                            Intent intent = new Intent(BindSchoolActivity.this, MySchoolActivity.class);
                            intent.putExtra("school_id", school);
                            intent.putExtra("school_name", schoolName);
                            startActivity(intent);
                            ToastUtil.show("绑定成功");
                            finish();
                        } else {
                            ToastUtil.show("绑定失败");
                        }

                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();
            }

            @Override
            public void onCompleted() {
                super.onCompleted();


            }
        });
    }

}
